package com.yuju.scheduler.service.task;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.yuju.cache.RedisCache;
import com.yuju.constant.CacheKey;
import com.yuju.constant.Constant;
import com.yuju.order.enums.ReserveStatusEnum;
import com.yuju.order.model.ReserveModel;
import com.yuju.order.service.IReserverService;
import com.yuju.util.DateUtil;
import com.yuju.util.Utils;

/**
 * 
 * 类名：FailureOrderHandler  <br />
 *
 * 功能：失效订单处理
 *
 * @author : xuehj <br />
 * @Date : 2018年1月19日 上午10:36:08  <br />
 * @version : 1.1 <br />
 */
@Component
public class FailureOrderHandler {
	private RedisCache<String, String> cache = RedisCache.getInstance();
	
	@Autowired
	private IReserverService reserverService;
	
	/**
	 * 定时任务，每隔2分钟执行一次
	 * 处理过期订单
	 **/
	@Scheduled(cron="0 */2 * * * ?")
	public void handler() {
		ReserveModel model = new ReserveModel();
		model.setReserveStatus(ReserveStatusEnum.WAITFORPAY.getValue());
		List<ReserveModel> reserveList = reserverService.list(model);
		for (ReserveModel reserve : reserveList) {
			// 失效分钟数
			String minutes = cache.get(reserve.getGroupId() + Constant.FAILURE_MINUTES_ORDER + CacheKey.KEY_GRP_PARAM);	
			if (Utils.isNull(minutes)) {
				continue ;
			}
			Date failureOrderDate = DateUtil.addMinutes(reserve.getGmtCreate(), Integer.valueOf(minutes));
			long time = DateUtil.compare(failureOrderDate, new Date());

			// 大于0，订单未过期，小于0，订单已过期
			if (time > 0) {
				continue ;
			}
			
			// 说明订单已过期，更新订单状态为“取消状态”			
			ReserveModel updateModel = new ReserveModel();
			updateModel.setId(reserve.getId());
			updateModel.setReserveStatus(ReserveStatusEnum.QUXIAO.getValue());
			reserverService.updateSelective(updateModel);
		}
	}
}
